<!--级联选择器-->

<template>
  <div class="w-h-full" :style="{
    textAlign: 'center',
    lineHeight: $parent.$parent.layoutItem.layoutItemConfigData.height - 2 + 'px'
  }">
    <!--组件遮罩层，用于在设计器中显示-->
    <div v-if="shade" class="shade"></div>

    <Cascader :data="cascaderData"
              :disabled="component.compConfigData.disabled"
              :filterable="component.compConfigData.filterable"
              :clearable="component.compConfigData.clearable"
              :size="component.compConfigData.size"
              :placeholder="component.compConfigData.placeholder"
              :notFoundText="component.compConfigData.notFoundText"
              v-model="value"
              :style="Object.assign({
                width: component.compConfigData.inputStyle.width,
                transform: 'scale('+component.compConfigData.inputStyle.scaleValue+')'
              }, inputStyleObject)"
              @on-change="onChangeHandle"
              @on-clear="onClearHandle"></Cascader>
  </div>
</template>

<script>

  import FuncCompMixin from '@/mixin/FuncCompMixin'
  import PnDesigner from '@/utils/PnDesigner'

  const _this = {
    name: 'CascaderComp', // 此名称必须填写，且必须与组件文件名相同
    mixins: [FuncCompMixin],
    attr: {
      version: '1.0',
      configDataTemp: Object.assign({

        disabled: false,
        clearable: false,
        filterable: false,
        size: 'large',
        placeholder: '请选择',
        notFoundText: '',
        trigger: 'click',

        inputStyle: {
          width: '150px',
          scaleValue: 1,
          backgroundColor: '#263238',
          color: '#fff',
          borderColor: '#2196f3'
        },

        sendDataType: 'all', // 交互流中发送数据类型，all：取所有值，last：取最后一个值
        datasourceType: 'children', // children、pid

        onChangeCode: '',
        onClearCode: ''

      }, PnDesigner.buildFuncCompDatasourceField({ // 如果组件需要配置数据源，则需要调用此函数构建数据源字段对象
        ds_resultObjTemplate: [
          {
            field: 'label',
            remark: '标签，必须项'
          },
          {
            field: 'value',
            remark: '值，必须项'
          },
          {
            field: 'children',
            remark: '子节点'
          },
          {
            field: 'id',
            remark: '唯一标识，当数据源结果集类型为pid类型时，必须定义id'
          },
          {
            field: 'pid',
            remark: '当数据源结果集类型为pid类型时，使用pid来关联父节点'
          },
        ],
        ds_resultObj: [
          {
            label: '广西壮族自治区',
            value: 'guangxi',
            children: [
              {
                label: '南宁市',
                value: 'nanning',
              },
              {
                label: '桂林市',
                value: 'guilin',
              },
              {
                label: '柳州市',
                value: 'liuzhou',
              },
              {
                label: '北海市',
                value: 'beihai',
              }
            ]
          }
        ],
        ds_useFilter: true, // 是否使用过滤器，默认不使用
        ds_useTimer: false, // 是否开启定时器配置，默认不开启
      }), PnDesigner.buildFuncCompGlobalField(), PnDesigner.buildFuncCompInteractionConfiguration([
        PnDesigner.buildFuncCompInteractionStreamItem('itemChange', [
          PnDesigner.buildFuncCompInteractionFieldsMapItem('label','', '标签'),
          PnDesigner.buildFuncCompInteractionFieldsMapItem('value','', '值'),
        ]),
        PnDesigner.buildFuncCompInteractionStreamItem('itemClear', [
          PnDesigner.buildFuncCompInteractionFieldsMapItem('label','', '标签'),
          PnDesigner.buildFuncCompInteractionFieldsMapItem('value','', '值')
        ])
      ]))
    },
    data() {
      return {
        value: [],
        // pidData: [
        //   {
        //     "id": "1",
        //     "label": "广西壮族自治区",
        //     "value": "guangxi",
        //     "pid": ""
        //   },
        //   {
        //     "id": "1-1",
        //     "label": "南宁市",
        //     "value": "nanning",
        //     "pid": "1"
        //   }
        // ]
      }
    },
    mounted() {
      this.init();
    },
    methods: {
      init () { // 组价初始化函数，函数名必须使用init，不可更改
        this.initDatasource(() => {
          this.runCustomGlobalJsCode()
        }, (result) => {
          this.runCustomGlobalJsCode()
        });
      },

      arrToTree (data) {
        let result = []
        if (!Array.isArray(data)) {
          return result
        }
        data.forEach(item => {
          delete item.children;
        });
        let map = {};
        data.forEach(item => {
          map[item.id] = item;
        });
        data.forEach(item => {
          let parent = map[item.pid];
          if (parent) {
            (parent.children || (parent.children = [])).push(item);
          } else {
            result.push(item);
          }
        });
        return result;
      },

      onChangeHandle (value, selectedData) {
        let labels = selectedData.map(function (params) {
          return params.label
        })
        let sendObj = {}
        switch (this.component.compConfigData.sendDataType) {
          case "all":
            sendObj = {label: labels.toString(), value: value.toString()}
            break
          case "last":
            sendObj = {label: labels.pop(), value: value.pop()}
            break
        }
        this.$PnDesigner.launchInteractionStream(this.component.compConfigData, 'itemChange', sendObj)
        eval(this.component.compConfigData.onChangeCode)
      },
      onClearHandle () {
        this.$PnDesigner.launchInteractionStream(this.component.compConfigData, 'itemClear', {label: '', value: ''})
        eval(this.component.compConfigData.onClearCode)
      }
    },
    computed: {
      cascaderData () {
        let ds_resultObj = this.$PnUtil.deepClone(this.component.compConfigData.ds_resultObj)
        ds_resultObj = this.runCustomFilter(ds_resultObj)
        if (this.component.compConfigData.datasourceType == 'pid') {
          if (Array.isArray(ds_resultObj) && ds_resultObj[0].pid != undefined) {
            ds_resultObj = this.arrToTree(ds_resultObj)
          }
        }
        return ds_resultObj
      },
      inputStyleObject () {
        return {
          '--background-color': this.component.compConfigData.inputStyle.backgroundColor,
          '--color': this.component.compConfigData.inputStyle.color,
          '--border-color': this.component.compConfigData.inputStyle.borderColor,
        }
      }
    }
  };

  export default _this
</script>

<style scoped>
  >>> .ivu-cascader {
    display: inline-block;
  }
  >>> .ivu-input {
    background-color: var(--background-color) !important;
    border: 1px solid var(--border-color) !important;
  }
  >>> .ivu-input::-webkit-input-placeholder{
    color: var(--color) !important;
  }
  >>> .ivu-input::-moz-placeholder{
    color: var(--color) !important;
  }
  >>> .ivu-cascader-arrow {
    color: var(--color) !important;
  }
</style>
